package com.mvp.lt.airlineview.map;

import android.content.Context;

import androidx.databinding.DataBindingUtil;

import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.CoordinateConverter;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.GroundOverlay;
import com.amap.api.maps.model.GroundOverlayOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.ServiceSettings;
import com.mvp.lt.airlineview.R;
import com.mvp.lt.airlineview.databinding.DroneStartPointMarkerBinding;
import com.mvp.lt.airlineview.utils.AndroidUtil;
import com.mvp.lt.airlineview.utils.LogUtil;
import com.mvp.lt.airlineview.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;

import static com.mvp.lt.airlineview.App.getContext;


public class MapCreateManager {
    private static final String TAG = "MapCreateManager";
    private AMap aMap;
    private MapView textureMapView;
    private Context mContext;
    LatLonPoint centerLatLng = new LatLonPoint(27.259653, 111.54144);
    private static MapCreateManager mapCreateManager;
    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);
    public CoordinateConverter converter = new CoordinateConverter(getContext());
    private LatLng myLatLng;
    private AMap.OnMarkerClickListener onMarkerClickListener;
    private AMap.OnMapClickListener onMapClickListener;
    private AMap.OnInfoWindowClickListener infoWindowClickListener;
    private AMap.OnMyLocationChangeListener onMyLocationChangeListener;
    private AMap.OnMarkerDragListener onMarkerDragListener;

    public LatLng getMyLatLng() {
        return myLatLng;
    }
//private CameraPosition mCameraPosition;

    public void setOnMarkerClickListener(AMap.OnMarkerClickListener onMarkerClickListener) {
        this.onMarkerClickListener = onMarkerClickListener;
    }

    public void setOnMapClickListener(AMap.OnMapClickListener onMapClickListener) {
        this.onMapClickListener = onMapClickListener;
    }

    public void setInfoWindowClickListener(AMap.OnInfoWindowClickListener infoWindowClickListener) {
        this.infoWindowClickListener = infoWindowClickListener;
    }

    public void setOnMyLocationChangeListener(AMap.OnMyLocationChangeListener onMyLocationChangeListener) {
        this.onMyLocationChangeListener = onMyLocationChangeListener;
    }

    //拖拽
    public void setOnMarkerDragListener(AMap.OnMarkerDragListener onMarkerDragListener) {
        this.onMarkerDragListener = onMarkerDragListener;
    }

    public AMap getaMap() {
        if (textureMapView == null) {
            return null;
        }
        if (aMap == null) {
            aMap = textureMapView.getMap();
        }
        return aMap;
    }

    /**
     * 长度
     *
     * @param latLngs
     * @return 单位米
     */

    public int getLatLngsLengh(List<LatLng> latLngs) {
        int length = 0;
        if (latLngs != null && latLngs.size() > 1) {
            for (int i = 0; i < latLngs.size() - 1; i++) {
                LatLng latLng1 = latLngs.get(i);
                LatLng latLng2 = latLngs.get(i + 1);
                length = length + (int) MapCalculationLogLatDistance.getDistanceTwoMi(latLng1.longitude, latLng1.latitude, latLng2.longitude, latLng2.latitude);
            }
        }
        return length;
    }

    /**
     * 单一实例
     */
    public static MapCreateManager getMapManager() {
        if (mapCreateManager == null) {
            mapCreateManager = new MapCreateManager();
        }
        return mapCreateManager;
    }

    public MapCreateManager setMapView(Context context,MapView textureMapView) {
        this.mContext = context;
        this.textureMapView = textureMapView;
        return mapCreateManager;
    }

    public void buildMap(Bundle savedInstanceState) {
        ServiceSettings.updatePrivacyShow(mContext, true, true);
        ServiceSettings.updatePrivacyAgree(mContext,true);
        onCreate(savedInstanceState);
        initMap();
    }

    public void onCreate(Bundle savedInstanceState) {
        textureMapView.onCreate(savedInstanceState);
    }

    public void moveToZoom(LatLng latLng, float var1) {
        if (aMap != null) {
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, var1));
        }
    }

    private void initMap() {

        aMap = textureMapView.getMap();
        aMap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层
//        aMap.setMinZoomLevel(5.5f);
//        aMap.setMaxZoomLevel(20f);
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(centerLatLng.getLatitude(), centerLatLng.getLongitude()), 16));
        /*LatLng northeastLatLng = new LatLng(32.128307, 114.582332);//东北
        LatLng southwestLatLng = new LatLng(22.702903, 108.54866);//西南l
        LatLngBounds latLngBounds = new LatLngBounds(southwestLatLng, northeastLatLng);
        aMap.setMapStatusLimits(latLngBounds);*/
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        setupLocationStyle();
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                //mCameraPosition = cameraPosition;
                //获取缩放级别
                LogUtil.e("tests", "当前地图缩放级别: " + cameraPosition.zoom);

            }
        });
        aMap.setTrafficEnabled(false);

        aMap.setOnMarkerDragListener(new AMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDragStart(Marker marker) {
                if (onMarkerDragListener != null) {
                    onMarkerDragListener.onMarkerDragStart(marker);
                }
            }

            @Override
            public void onMarkerDrag(Marker marker) {
                if (onMarkerDragListener != null) {
                    onMarkerDragListener.onMarkerDrag(marker);
                }
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                if (onMarkerDragListener != null) {
                    onMarkerDragListener.onMarkerDragEnd(marker);
                }
            }
        });
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (onMarkerClickListener != null) {
                    onMarkerClickListener.onMarkerClick(marker);
                }

                return true;//true不移动到中心位置 ，false逸动到中心位置
            }
        });

        aMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                LogUtil.e("地图", "=======================滑动======================");
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {

                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    MapCreateManager.getMapManager().getaMap().getUiSettings().setScrollGesturesEnabled(true);
                } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {

                }
            }
        });
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (onMapClickListener != null) {
                    onMapClickListener.onMapClick(latLng);
                }
            }
        });

        aMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                //自定义内容的和窗口背景
//                return customInfoWindowMarker(marker);
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                //自定义内容
                return null;
            }
        });

        aMap.setOnInfoWindowClickListener(new AMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                if (infoWindowClickListener != null) {
                    infoWindowClickListener.onInfoWindowClick(marker);
                }
            }
        });
        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setMyLocationButtonEnabled(false); // 是否显示定位按钮
        mUiSettings.setZoomControlsEnabled(false);//设置地图默认的缩放按钮是否显示
        mUiSettings.setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_BUTTOM);
        mUiSettings.setScaleControlsEnabled(false);//比列尺
        mUiSettings.setRotateGesturesEnabled(false); //禁止地图旋转手势.
        mUiSettings.setTiltGesturesEnabled(false);
        mUiSettings.setLogoBottomMargin(-57);//隐藏logo
        mUiSettings.setLogoLeftMargin(-57);//隐藏logo

        // aMap.setLocationSource(this);// 设置定位监听
        //设置SDK 自带定位消息监听
        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                //自己的位置
                // 定位回调监听
                if (location != null) {
                    Log.e("amap", "onMyLocationChange 定位成功， lat: " + location.getLatitude() + " lon: " + location.getLongitude());
                    myLatLng = new LatLng(location.getLatitude(), location.getLongitude());
                    Bundle bundle = location.getExtras();
                    if (bundle != null) {
                        int errorCode = bundle.getInt(MyLocationStyle.ERROR_CODE);
                        String errorInfo = bundle.getString(MyLocationStyle.ERROR_INFO);
                        // 定位类型，可能为GPS WIFI等，具体可以参考官网的定位SDK介绍
                        int locationType = bundle.getInt(MyLocationStyle.LOCATION_TYPE);

                        //将地图移动到定位点
                        Log.e("amap", "定位信息， code: " + errorCode + " errorInfo: " + errorInfo + " locationType: " + locationType);
                    } else {
                        Log.e("amap", "定位信息， bundle is null ");

                    }

                } else {
                    Log.e("amap", "定位失败");
                }

                if (onMyLocationChangeListener != null) {
                    onMyLocationChangeListener.onMyLocationChange(location);
                }
            }
        });

    }


    /**
     * 设置自定义定位蓝点
     */
    public void setupLocationStyle() {
        // 自定义系统定位蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.gps_point));
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(STROKE_COLOR);
        //自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(5);
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(FILL_COLOR);
        myLocationStyle.interval(5000);
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);
//        aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));//只展示位置
        aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));//实时定位
    }

    public void onSaveInstanceState(Bundle outState) {
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        if (textureMapView != null) {
            textureMapView.onSaveInstanceState(outState);
        }
    }

    public void onDestroy() {
        //LocationAmpUtils.getInstance().onDestroy();
        if (textureMapView != null) {
            //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
            textureMapView.onDestroy();
            textureMapView = null;
        }
        aMap = null;
        mapCreateManager = null;
        myLatLng = null;
        onMapClickListener = null;
        onMarkerClickListener = null;
        onMyLocationChangeListener = null;
        infoWindowClickListener = null;

    }


    public Polyline drawLine(List<LatLng> latLngs) {
        return aMap.addPolyline(new PolylineOptions().color(Color.BLUE)
                .addAll(latLngs)
                .useGradient(true)
                .width(5));
    }


    public Polyline drawLineBlackGray(List<LatLng> latLngs) {
        return aMap.addPolyline(new PolylineOptions().color(Color.RED)
                .addAll(latLngs)
                .useGradient(true)
                .width(10));
    }

    public Polyline drawLineBlackGreen(List<LatLng> latLngs) {
        return aMap.addPolyline(new PolylineOptions().color(Color.BLUE)
                .addAll(latLngs)
                .useGradient(true)
                .width(10));
    }

    public Polyline drawLineBlackGreenMagen(List<LatLng> latLngs) {
        return aMap.addPolyline(new PolylineOptions().color(Color.MAGENTA)
                .addAll(latLngs)
                .useGradient(true)
                .width(10));
    }

    public Polyline drawLineYellow(List<LatLng> latLngs) {
        return aMap.addPolyline(new PolylineOptions().color(Color.YELLOW)
                .addAll(latLngs)
                .useGradient(true)
                .width(5));
    }

    public Polyline drawLineRed(List<LatLng> latLngs) {
        return aMap.addPolyline(new PolylineOptions().color(Color.RED)
                .addAll(latLngs)
                .useGradient(true)
                .width(5));
    }

    public void onResume() {
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        if (textureMapView != null) {
            textureMapView.onResume();

        }
    }

    public void onPause() {
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        if (textureMapView != null) {
            textureMapView.onPause();

        }
    }


    public void expansionLine(double droneLng, double droneLat, double targetLng, double targetLat, double percentagedata) {
        LatLng latLng = MapCalculationLogLatDistance.getDistanceExpansionPoint(targetLat, targetLng, droneLat, droneLng, 1.0);

    }


    /**
     * 放大
     */
    public void scaleLargeMap() {
        CameraPosition cameraPosition = aMap.getCameraPosition();
        float mapZoom = cameraPosition.zoom;
        LatLng mapTarget = cameraPosition.target;
        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mapTarget, ++mapZoom));
    }

    /**
     * 缩小
     */
    public void scaleSmallMap() {
        CameraPosition cameraPosition = aMap.getCameraPosition();
        float mapZoom = cameraPosition.zoom;
        LatLng mapTarget = cameraPosition.target;
        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mapTarget, --mapZoom));
    }

    /**
     * 切换地图模式
     */
    public void mapType(int type) {
        if (type != 0) {
            aMap.setMapType(type);
        }
    }


    public void mapTraffic(boolean traffic) {
        aMap.setTrafficEnabled(traffic);//显示实时路况图层，aMap是地图控制器对象。
    }

    /**
     * -180~0~（180）转逆时针方位角0-360
     * <p>
     * -90  -> 90
     * 90   -> 270
     *
     * @param value
     * @return
     */
    public static double parseYawToAntiClockwise360(double value) {
        double yaw = 0;
        try {
            if (value < 0) {
                yaw = -value;
            } else if (value > 0) {
                yaw = 360 - value;
            } else {
                yaw = value;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return yaw;
    }

    /**
     * 把地图Marker点的角度转换成航点机头角度Heading参数
     * 角度转换0~360（顺时针针）转成飞机方位角-180~ 180
     * 90-> 90
     * 270 ->-90
     *
     * @param value -90   90
     * @return
     */
    public static double parseMarkerAzimuthAngleToUAVHeading(double value) {
        double yaw = 0;
        if (value > 180) {
            yaw = value - 360;
        } else if (value < 180) {
            yaw = value;
        } else {
            yaw = value;
        }
        return yaw;
    }

    /**
     * 地球经纬度范围
     *
     * @param latitude
     * @param longitude
     * @return
     */
    public boolean checkGpsCoordinate(double latitude, double longitude) {
        return (latitude > -90 && latitude < 90 && longitude > -180 && longitude < 180) && (latitude != 0f
                && longitude != 0f);
    }


    /**
     * 经纬度有效范围
     * (latitude > -90 && latitude < 90 && longitude > -180 && longitude < 180)
     * 中国经纬度范围
     * 73°33′E至135°05′E。纬度范围：3°51′N至53°33′N
     *
     * @param latitude  纬度
     * @param longitude 经度
     * @return boolean
     */
    public static boolean checkGpsCoordinates(double latitude, double longitude) {
        return (latitude > 3.51 && latitude < 53.33 && longitude > 73.33 && longitude < 135.05);
    }

    public LatLng latLngGpsToGDLatLng(LatLng sourceLatLng, Context context) {
        if (converter == null) {
            converter = new CoordinateConverter(context);
        }
        // CoordType.GPS 待转换坐标类型
        converter.from(CoordinateConverter.CoordType.GPS);
        // sourceLatLng待转换坐标点 LatLng类型
        converter.coord(sourceLatLng);
        // 执行转换操作
        LatLng desLatLng = converter.convert();
        return desLatLng;
    }


    /**
     * 画出飞机和目标点的连线 纹理线
     */
    public Polyline drawTargetLine(LatLng targetLatLng, LatLng aircraftLatLng) {
        try {
            PolylineOptions opts = new PolylineOptions();
            List<LatLng> points = new ArrayList<LatLng>();
            points.add(aircraftLatLng);
            points.add(targetLatLng);
            opts.addAll(points);
            opts.setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.map_alr_night));
            opts.width(5);
            opts.color(0xFFFF0000);
            return aMap.addPolyline(opts);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 画出飞机和Home点的连线 虚线
     */
    public Polyline drawTwoPointLine(List<LatLng> sparseArray) {
        if (sparseArray == null || sparseArray.size() < 2) {
            return null;
        }
        return drawTwoPointBlueLine(sparseArray.get(sparseArray.size() - 2), sparseArray.get(sparseArray.size() - 1));
    }


    /**
     * 中心线
     *
     * @param sparseArray
     * @return
     */
    public Polyline drawTwoPointBlue10Line(List<LatLng> sparseArray) {
        if (sparseArray == null || sparseArray.size() < 2) {
            return null;
        }
        return drawTwoDashBlue10Line(sparseArray.get(sparseArray.size() - 2), sparseArray.get(sparseArray.size() - 1));
    }


    public Polyline drawTwoDashBlue10Line(LatLng LatLng1, LatLng LatLng2) {
        try {
            PolylineOptions opts = new PolylineOptions();
            List<LatLng> points = new ArrayList<LatLng>();
            points.add(LatLng1);
            points.add(LatLng2);
            opts.width(8);
            opts.addAll(points);
            opts.color(AndroidUtil.getColor(R.color.dodgerblue));
            return aMap.addPolyline(opts);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public Polyline drawTwoDashBlueLine(LatLng LatLng1, LatLng LatLng2) {
        try {
            PolylineOptions opts = new PolylineOptions();
            List<LatLng> points = new ArrayList<LatLng>();
            points.add(LatLng1);
            points.add(LatLng2);
            opts.width(5);
            opts.addAll(points);
            opts.setDottedLine(true);
            opts.color(AndroidUtil.getColor(R.color.dodgerblue));
            return aMap.addPolyline(opts);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 画两点的连线
     */
    public Polyline drawTwoPointBlueLine(LatLng LatLng1, LatLng LatLng2) {
        try {
            PolylineOptions opts = new PolylineOptions();
            List<LatLng> points = new ArrayList<LatLng>();
            points.add(LatLng1);
            points.add(LatLng2);
            opts.addAll(points);
            opts.width(5);
            opts.color(AndroidUtil.getColor(R.color.deepskyblue));
            return aMap.addPolyline(opts);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public Polyline drawTwoWayPointBlueLine(List<LatLng> latLngs) {
        try {
            PolylineOptions opts = new PolylineOptions();
            opts.addAll(latLngs);
            opts.width(4);
            opts.zIndex(8);
            opts.color(AndroidUtil.getColor(R.color.mediumspringgreen));
            return aMap.addPolyline(opts);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public Polyline drawDashBlueLine(List<LatLng> latLngs) {
        try {
            PolylineOptions opts = new PolylineOptions();
            opts.addAll(latLngs);
            opts.width(5);
            opts.setDottedLine(true);
            opts.zIndex(5);
            opts.color(AndroidUtil.getColor(R.color.dodgerblue));
            return aMap.addPolyline(opts);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 起始点
     * 11
     *
     * @param context
     * @param latLng
     * @return
     */
    public Marker setStartAndEndMarkerView(Context context, LatLng latLng, String msg) {
        DroneStartPointMarkerBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.drone_start_point_marker, null, false);
        binding.tvName.setText(msg);
        MarkerOptions markerOptions = new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromView(binding.getRoot())).position(latLng)
                .anchor(0.5f, 0.5f);
        Marker marker = MapCreateManager.getMapManager().getaMap().addMarker(markerOptions);
        marker.setZIndex(10);
        marker.setDraggable(false);
        marker.setClickable(false);
        return marker;
    }

    /**
     * 画虚线
     */
    public Polyline drawDashLine(List<LatLng> latLngLists) {
        try {
            if (aMap != null) {
                PolylineOptions opts = new PolylineOptions();
                opts.addAll(latLngLists);
                opts.setDottedLine(true);
                opts.width(8);
                opts.color(0xFFF1BB07);
                return aMap.addPolyline(opts);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * 画出飞机和Home点的连线 虚线
     */
    public Polyline drawLine(LatLng targetLatLng, LatLng aircraftLatLng) {
        try {
            PolylineOptions opts = new PolylineOptions();
            List<LatLng> points = new ArrayList<LatLng>();
            points.add(aircraftLatLng);
            points.add(targetLatLng);
            opts.addAll(points);
//            opts.setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.map_alr_night));
            opts.width(8);
            opts.setDottedLine(true);
            opts.color(0xff1ce695);
            return aMap.addPolyline(opts);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public Marker addMarker(LatLng latLng) {
        MarkerOptions markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
                .position(latLng);
        return aMap.addMarker(markerOption);
    }


    public Marker addMarker1(LatLng latLng) {
        MarkerOptions markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
                .position(latLng);
        return aMap.addMarker(markerOption);
    }

    public Marker addMarker2(LatLng latLng) {

        MarkerOptions markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_ROSE))
                .position(latLng)
                .draggable(true);
        return aMap.addMarker(markerOption);
    }

    public Marker addMarker3(LatLng latLng) {
        MarkerOptions markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
                .position(latLng)
                .draggable(true);
        return aMap.addMarker(markerOption);
    }

    private boolean isLocation = false;

    private boolean isAutoAnimateCamera = false;

    /**
     * 自动缩放 显示所有点
     *
     * @param latLngs
     */
    public void autoAnimateCameraMap(List<LatLng> latLngs, AMap.CancelableCallback listener) {
        if (latLngs != null && latLngs.size() > 0) {
            LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();//存放所有点的经纬度
            for (int i = 0; i < latLngs.size(); i++) {
                boundsBuilder.include(latLngs.get(i));//把所有点都include进去（LatLng类型）
            }
            isLocation = true;
            isAutoAnimateCamera = true;
            LogUtil.e("航点", "保存------------------autoAnimateCameraMap---");
            aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(boundsBuilder.build(), UIUtils.dip2Px(110)), 600, new AMap.CancelableCallback() {
                @Override
                public void onFinish() {
                    if (listener != null) {
                        listener.onFinish();
                    }
                    isAutoAnimateCamera = false;
                }

                @Override
                public void onCancel() {
                    if (listener != null) {
                        listener.onCancel();
                    }
                    isAutoAnimateCamera = false;
                }
            });//第二个参数为四周留空宽度
        } else {
            if (myLatLng != null) {
                isLocation = true;
                moveToLocation(myLatLng, 19);
            }
        }

    }

    /**
     * 自动缩放 显示所有点
     *
     * @param latLngs
     */
    public void autoAnimateCameraMap(List<LatLng> latLngs) {
        autoAnimateCameraMap(latLngs, null);
    }

    public void moveToZoom(LatLng latLng) {
        moveToLocation(latLng);
    }

    public void moveToLocation(LatLng latLng) {
        moveToLocation(latLng, 15);
    }

    /**
     * interest_point_marker_off
     */
    public void moveTolocation() {
        if (aMap != null && myLatLng != null) {
            //将地图移动到定位点
            isLocation = true;
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLatLng, 15));
        }
    }

    public void moveToLocation(LatLng latLng, int scale) {
        if (aMap != null && myLatLng != null && !isAutoAnimateCamera) {
            //将地图移动到定位点
            isLocation = true;
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, scale));
        }
    }

    /**
     * 画面
     *
     * @param linelatLngs
     * @param color
     * @param color2
     * @return
     */
    public Polygon drawPolygonOptions(List<LatLng> linelatLngs, int color, int color2) {
        PolygonOptions polygonOptions = new PolygonOptions();
        polygonOptions.addAll(linelatLngs);
        polygonOptions.strokeWidth(0) // 多边形的边框
                .strokeColor(color) // 边框颜色
                .zIndex(6)
                .fillColor(color2);   // 多边形的填充色
        return aMap.addPolygon(polygonOptions);
    }

    public Polyline drawBlueLine(List<LatLng> latLngs) {
        return aMap.addPolyline(new PolylineOptions().color(Color.BLUE)
                .addAll(latLngs)
                .useGradient(true)
                .width(5));
    }

    /**
     * 起始点
     *
     * @param context
     * @param latLng
     * @return
     */
    public Marker setStartMarkerView(Context context, LatLng latLng, String msg) {
        DroneStartPointMarkerBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.drone_start_point_marker, null, false);
        binding.tvName.setText(msg);
        MarkerOptions markerOptions = new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromView(binding.getRoot())).position(latLng)
                .anchor(0.5f, 0.5f);
        Marker marker = MapCreateManager.getMapManager().getaMap().addMarker(markerOptions);
        marker.setZIndex(11);
        marker.setDraggable(false);
        marker.setClickable(false);
        return marker;
    }

    /**
     * 两点式
     *
     * @param x1
     * @param y1
     * @param x2
     * @param y2
     * @param x
     * @return
     */
    private float getCrossPoint(float x1, float y1, float x2, float y2, float x) {
        float k = (y2 - y1) / (x2 - x1);
        float y = k * (x - x1) + y1;
        return y;
    }


    /**
     * 两点式
     *
     * @param x1               起始点x1
     * @param y1               起始点y1
     * @param x2               目标点x2
     * @param y2               目标点y2
     * @param bisectionTargetX 目标点等分
     * @return
     */
    private float getBisectionPoint(float x1, float y1, float x2, float y2, int bisectionTargetX) {
        float x = (x2 - x1) / bisectionTargetX;

        float k = (y2 - y1) / (x2 - x1);
        float y = k * (x - x1) + y1;
        return y;
    }


    //计算
    public void calculation(List<LatLng> latLngs) {
        // 计算面积
        double s = workOutArea(latLngs);//平方千米
        // 计算边长
        double slideLength = workSideLength(latLngs);//千米
        // 计算周长，即 边长+第一点和最后一点的距离
        double girthLength = workGirthLength(latLngs, slideLength);//千米

    }

    /**
     * 计算面积
     * 平方千米
     *
     * @param latLngs
     * @return
     */
    public double workOutArea(List<LatLng> latLngs) {
        if (latLngs.size() < 3) {
            return 0;
        }
        int j = 0;
        double s = 0;
        for (int i = 0; i < latLngs.size(); i++) {
            j = i + 2;
            double a = MapCalculationLogLatDistance.GetDistanceTwo(latLngs.get(0).longitude, latLngs.get(0).latitude, latLngs.get(i + 1).longitude, latLngs.get(i + 1).latitude);
            double b = MapCalculationLogLatDistance.GetDistanceTwo(latLngs.get(i + 1).longitude, latLngs.get(i + 1).latitude, latLngs.get(i + 2).longitude, latLngs.get(i + 2).latitude);
            double c = MapCalculationLogLatDistance.GetDistanceTwo(latLngs.get(0).longitude, latLngs.get(0).latitude, latLngs.get(i + 2).longitude, latLngs.get(i + 2).latitude);
            double p = (a + b + c) / 2;
            s += Math.sqrt(p * (p - a) * (p - b) * (p - c));
            if (j >= latLngs.size() - 1) {
                break;
            }
        }
        return s;
    }

    /**
     * 计算边长
     *
     * @return
     */
    public double workSideLength(List<LatLng> latLngs) {
        if (latLngs.size() < 2) {
            return 0;
        }
        double sum = 0;
        int j = 0;
        for (int i = 0; i < latLngs.size(); i++) {
            double a = MapCalculationLogLatDistance.GetDistanceTwo(latLngs.get(i).longitude, latLngs.get(i).latitude, latLngs
                    .get(i + 1).longitude, latLngs.get(i + 1).latitude) / 1000;
            sum += a;
            j = i + 1;
            if (j >= latLngs.size() - 1) {
                break;
            }
        }
        return sum;
    }

    /**
     * 计算周长
     *
     * @param length 边长
     * @return
     */
    public double workGirthLength(List<LatLng> latLngs, double length) {
        double roundLength = 0;
        if (latLngs.size() < 3) {
            return length;
        }
        double a = MapCalculationLogLatDistance.GetDistanceTwo(latLngs.get(0).longitude, latLngs.get(0).latitude,
                latLngs.get(latLngs.size() - 1).longitude, latLngs.get(latLngs.size() - 1).latitude) / 1000;
        roundLength = length + a;
        return roundLength;
    }

    /**
     * 左
     *
     * @param value
     * @return 0-360 顺时针
     */
    public int parseLeftRotationToHead(int value) {
        int tempAngle = 0;
        if (value < 0) {
            tempAngle = value + 360;
        } else {
            tempAngle = value;
        }
        tempAngle = tempAngle + 90;
        if (tempAngle >= 360) {
            tempAngle = Math.abs(tempAngle - 360);
        }
        tempAngle = parseYawAnticlockwise(tempAngle);
        return tempAngle;
    }

    /**
     * 上方
     *
     * @param value
     * @return 0-360 顺时针
     */
    public int parseCenterOrTopRotationToHead(int value) {
        int tempAngle = 0;
        tempAngle = value - 90;
        if (tempAngle < 0) {
            tempAngle = tempAngle + 360;
        }
        tempAngle = parseYawAnticlockwise(tempAngle);
        return tempAngle;
    }

    /**
     * 右
     *
     * @param value
     * @return 0-360 顺时针
     */
    public int parseRightRotationToHead(int value) {
        int tempAngle = 0;
        tempAngle = value - 270;
        if (tempAngle < 0) {
            tempAngle = tempAngle + 360;
        }
        tempAngle = parseYawAnticlockwise(tempAngle);
        return tempAngle;
    }

    /**
     * 下
     *
     * @param value
     * @return 0-360 顺时针
     */
    public int parseBottomRotationToHead(int value) {
        int tempAngle = 0;
        if (value >= 360) {
            tempAngle = value - 360;
        } else {
            tempAngle = value;
        }
        tempAngle = tempAngle - 90;
        if (tempAngle < 0) {
            tempAngle = tempAngle + 360;
        }
        tempAngle = parseYawAnticlockwise(tempAngle);
        return tempAngle;
    }


    /**
     * 逆时针360度 = 顺时针360度  转换  或
     * 顺时针360度 = 逆时针360度  转换
     *
     * @param value
     * @return
     */
    public int parseYawAnticlockwise(int value) {
        int tempAngle = 0;
        if (value == 0 || value == 360) {
            tempAngle = 0;
        } else {
            tempAngle = 360 - value;
        }
        return tempAngle;
    }

    /**
     * 往地图上添加一个覆盖物
     *
     * @param path
     * @param latlng
     */
    public void addOverlayToMap(String path, LatLng latlng) {
        BitmapDescriptor groundOverlayOptions = BitmapDescriptorFactory.fromPath(path);
        GroundOverlay groundOverlay = aMap.addGroundOverlay(new GroundOverlayOptions()
                .anchor(0.5f, 0.5f)
                .transparency(0.2f)
                .zIndex(0.1f)
                .image(groundOverlayOptions)
                .position(latlng, 250 * 1.3f, 250));
        groundOverlay.setBearing(180);
        moveToLocation(latlng);
    }

    /**
     * 中心
     *
     * @param path
     * @param southwest
     * @param northeast
     * @param center
     */
    public void addOverlayBoundsToMap(String path, LatLng southwest, LatLng northeast, LatLng center) {
        LatLngBounds bounds = new LatLngBounds.Builder().include(southwest).include(northeast).build();
        BitmapDescriptor groundOverlayOptions = BitmapDescriptorFactory.fromPath(path);
        GroundOverlay groundOverlay = aMap.addGroundOverlay(new GroundOverlayOptions()
                .anchor(0.5f, 0.5f)
                .transparency(0.2f)
                .zIndex(0.1f)
                .image(groundOverlayOptions)
                .positionFromBounds(bounds));
        groundOverlay.setBearing(180);
        moveToLocation(center);
    }

}
